<?php

class UserPeer extends BaseUserPeer
{
  /**
   * Add a new user
   * @param array $infos {email, phone, name, address, city_id, postal_code} <<BasePeer::TYPE_FIELDNAME>>
   */
  public static function add(array $infos)
  {
    // validate the infos
    $check = self::validate($infos);
    if ($check !== true)
    {
      // $check is an array that contains the error messages for the corresponding fields
      return $check;
    }
    else
    {
      // create the user
      $user = new User();
      foreach ($infos as $field => $value)
      {
        // translate the field names into method names
        $setter = 'set'.ucfirst(self::translateFieldName($field, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_STUDLYPHPNAME));
        call_user_func(array($user, $setter), $value);
      }
      $user->save();

      return true;
    }
  }

  /**
   * Validate the user infos
   * 
   * @param array $infos
   * @return true | array
   */
  public static function validate(array $infos)
  {
    return true;
  }

  /**
   * Verify a user's credentials
   *
   * @param int $id
   * @param string $password
   * @return bool
   */
  public static function login($id, $password)
  {
    $id = trim($id);
    $user = self::retrieveByPK($id);
    if ($user && $user->getPassword() != myTools::encryptPassword($password))
    {
      $user = null;
    }
    
    $authenticated = $user ? $id : false;
    sfContext::getInstance()->getUser()->setAuthenticated($authenticated);

    return (bool)$authenticated;
  }
  
}
